package com.hdl.dao.impl;

import com.hdl.dao.AccountDao;
import com.hdl.pojo.Account;
import com.hdl.utils.ConnectionUtils;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author hedonglin
 * @date 2020/5/3 11:57
 * @description JDBC实现账户持久层
 */
public class JdbcAccountDaoImpl implements AccountDao {
    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    @Override
    public Account queryAccountByCardNo(String cardNo) throws Exception {
        // 1、获取一个数据库连接
//        DruidPooledConnection connection = DruidUtils.getInstance().getConnection();
//        Connection connection = ConnectionUtils.getInstance().getCurrentThreadConn();
        // 2、Sql准备
        String sql = "select cardNo, name, money from account where cardNo = ?";

        // 3、预编译和参数准备
        PreparedStatement statement = connectionUtils.getCurrentThreadConn().prepareStatement(sql);
        statement.setString(1, cardNo);

        // 4、执行查询
        ResultSet resultSet = statement.executeQuery();

        // 5、遍历查询结果
        Account account = new Account();
        while (resultSet.next()){
            account.setCardNo(resultSet.getString("cardNo"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
        }

        resultSet.close();
        statement.close();
//        connection.close();

        return account;
    }

    @Override
    public int updateAccountByCardNo(Account account) throws Exception {
        // 1、获取一个数据库连接
//        DruidPooledConnection connection = DruidUtils.getInstance().getConnection();
//        Connection connection = ConnectionUtils.getInstance().getCurrentThreadConn();
        // 2、Sql准备
        String sql = "update account set money=? where cardNo=?";

        // 3、预编译和参数准备
        PreparedStatement statement = connectionUtils.getCurrentThreadConn().prepareStatement(sql);
        statement.setInt(1,account.getMoney());
        statement.setString(2,account.getCardNo());

        // 4、执行更新
        int result = statement.executeUpdate();

        statement.close();
//        connection.close();
        return result;
    }
}
